//
//  oauthrequest.swift
//  swift一遍敲
//
//  Created by 刘耀宗 on 16/4/19.
//  Copyright © 2016年 刘耀宗. All rights reserved.
//

import UIKit
import SVProgressHUD

class oauthrequest: UIViewController,UIWebViewDelegate {
    override func loadView() {
        self.view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavigationBar()
     
        let url = NSURL.init(string: setURL())
        //请求
        let request = NSURLRequest.init(URL: url!)
        //加载
        webView.loadRequest(request)
        SVProgressHUD.showWithStatus("正在努力的加载")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
        
    }
    private func setNavigationBar()
    {
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "填充", style: UIBarButtonItemStyle.Done, target: self, action: #selector(oauthrequest.fillIn))
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "取消", style: UIBarButtonItemStyle.Done, target: self, action: #selector(oauthrequest.cancel))
        
    
    
    }
    @objc private func fillIn()
    {
        // 使用webView执行js代码
        let js = "document.getElementById('userId').value = '648731281@qq.com';document.getElementById('passwd').value = '53663168jin'"
        webView.stringByEvaluatingJavaScriptFromString(js)
        print("填充")
    
    }
    @objc private func cancel()
    {
        print("取消")
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    ////请求
   // https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
    private func setURL() ->String
        {
            let str = OauthUrl + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
            return str
    
    
    }

    private func loadloginView()
    {
        }
    private lazy var webView: UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        
        return webView
    
    }()
    //拦截数据
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlStr = request.URL?.absoluteString
        print("urlStr = \(urlStr)")
        if !urlStr!.hasPrefix(redirect_uri)
        {
            return true
        
        }
        else
        {
            let str = "code="
            //判断有没有code
            let backUrl = request.URL?.query
            if  backUrl!.hasPrefix(str){
                print("backUrl=\(backUrl)")
                //点击了授权
                print("点击了授权")
                let code = (backUrl! as NSString).substringFromIndex(str.characters.count)
                print("code=\(code)")
                  HMUserAccessModel.shareAccessModel.loadUserAcessToken(code, backallocate: { (error) in
                    if error != nil
                    {
                        print("登录失败")
                        self.cancel()
                    
                    }
                    else
                    {
                        print("登录成功")
                        UIApplication.sharedApplication().delegate?.window!!.rootViewController = HMMainTabbarVC()
                    
                    }
                    
                    
                  })
                
    
            
     
            return false
            }
        
 
        }
        
          return false
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        print("网页加载完毕")
        SVProgressHUD.dismiss()
    }
    //网页加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.showErrorWithStatus("网络不给力")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
        
    }

}
